package com.admin.web.controller;

import com.admin.bean.HttpResult;
import com.alibaba.fastjson.JSONObject;
import com.mongodb.gridfs.GridFSDBFile;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

@RestController
@RequestMapping("/app/file/")
public class FileController {

    @Resource
    private GridFsTemplate gridFsTemplate;

    @RequestMapping("download/{id}")
    public void download(HttpServletResponse response, @PathVariable String id) throws IOException {
        GridFSDBFile file = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(id)));
        if (file != null) {
            ServletOutputStream outputStream = response.getOutputStream();
            InputStream inputStream = file.getInputStream();
            response.setHeader("content-disposition", "attachment;filename=" + file.getFilename());
            response.setHeader("Content-Length", Long.toString(file.getLength()));
            IOUtils.copy(inputStream, outputStream);
        } else {
            response.getWriter().print(JSONObject.toJSONString(HttpResult.buildFail("找不到文件!")));
        }
    }

    @RequestMapping("view/{id}")
    public void viewFile(@PathVariable String id, String type, HttpServletResponse response) throws Exception {
        if (StringUtils.isEmpty(type)) {
            response.setHeader("Content-Type", "image/jpeg");
        } else {
            response.setHeader("Content-Type", type);
        }

        // response.setHeader("Age", "7729905");
        // response.setHeader("Cache-Control", "max-age=" + 20000);
        // response.setHeader("Cache-Control", "public");
        // response.setHeader("Pragma", "Pragma");
        // response.setDateHeader("Last-Modified", currentTimeMillis);
        // response.setDateHeader("Expires", currentTimeMillis + 2000000000);
        Query query = Query.query(Criteria.where("_id").is(id));
        GridFSDBFile gridFSDBFile = gridFsTemplate.findOne(query);
        response.setDateHeader("expires", System.currentTimeMillis() + 1000 * 3600 * 1000 * 1000);
        response.setContentLength(Long.valueOf(gridFSDBFile.getLength()).intValue());
        InputStream inputStream = gridFSDBFile.getInputStream();
        IOUtils.copy(inputStream, response.getOutputStream());
        inputStream.close();
    }
}
